#include "Hierarchy.hpp"
#include <algorithm>

using namespace Typhoon;

Hierarchy::Hierarchy() 
	:
Parent(this)
{
	Parent = 0;
	Parent.ChangedWithOld += event_handler(this, &Hierarchy::ParentChanged);
}

Hierarchy::~Hierarchy() {
}

int Hierarchy::ChildrenCount() {
	return (int)children.size();
}

GameObject* Hierarchy::GetChild( int index ) {
	return children[index];
}

void Hierarchy::ParentChanged( Property<Hierarchy*, GameObject*>::EventData data )
{
	if (data.Old) {
		Children::iterator it = find(children.begin(), children.end(), gameObject);
		if (it!=children.end()) {
			data.Old->GetComponent<Hierarchy>()->children.erase(it);
		}
	}

	if (data.Current) {
		data.Current->GetComponent<Hierarchy>()->children.push_back(gameObject);
	}
}
